package batch.common.util;

public class HexUtil {
    public static String bytesToHex(byte b[]) {
        StringBuffer buf = new StringBuffer();

        for (int i=0 ; i<b.length ; i++) {
            buf.append(byteToHex(b[i]));
        }

        return buf.toString();
    }

    public static String byteToHex(byte b) {
        char[] hexChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };

        int high = ((b & 0xf0) >> 4);
        int low = (b & 0x0f);

        char[] chars = new char[2];
        chars[0] = hexChars[((b&0xf0)>>4)];
        chars[1] = hexChars[(b&0x0f)];

        return String.valueOf(chars);
    }

    public static byte[] hexToBytes(String sHexString) {
        byte[] b = new byte[sHexString.length()/2];

        for (int i=0 ; i<b.length ; i++) {
            b[i] = hexToByte(sHexString.substring(i*2, (i*2)+2));
        }

        return b;
    }

    public static byte hexToByte(String sHexString) {
        return (byte)((Byte.parseByte(sHexString.substring(0,1),16)<<4) | Byte.parseByte(sHexString.substring(1,2),16));
    }
}
